<?php
/***********************************************************
 * 回收站
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Console;
use think\facade\Cache;
use app\common\logic\ArctypeLogic;
use app\common\model\Arctype;

class RecycleBin extends Base
{
    public $arctype_channel_id;
    public $arctypeLogic;
    public $popedom = '';
    public function initialize() 
    {
        parent::initialize();
        $gzpcfglobal = get_global();
        $this->arctypeLogic = new ArctypeLogic(); 
        $this->arctype = new Arctype(); 
        $this->arctype_channel_id = $gzpcfglobal['arctype_channel_id'];   
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
    }

    // 回收站管理 - 栏目列表
    public function index()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            $post = input('param.');
            if(isset($post['limit'])){
                $limit = $post['limit'];
            }else{
                $limit = 10;
            }
            $keywords = isset($post['keywords'])?$post['keywords']:'';
            $condition = [];
            // 应用搜索条件
            if (!empty($keywords)) {
                $condition[] = ['typename','=',"{$keywords}"];
            }
            $condition[] = ['is_del','=',1];
            $list = Db::name('arctype')->field('id,typename,current_channel,update_time')->where($condition)->order('update_time desc')->paginate($limit);
            $list1 = $list->items();
            $channeltype_list = getChanneltypeList();
            foreach ($list1 as $key => $value) {
                $list1[$key]['update_time'] = pcftime($value['update_time']);
                $list1[$key]['current_channel'] = $channeltype_list[$value['current_channel']]['title'];
            }
            $result = ['code' => 0, 'data' => $list1,'count'=> $list->total()];
            return $result;
        }
        return $this->fetch();
    }

    // 回收站管理 - 栏目还原
    public function arctype_recovery()
    {
        if (Request::isPost()) {
            if(!$this->popedom["databack"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.databack')];
                    return $result;                    
                }
            }
            $del_id = input('post.del_id/d', 0);
            if(!empty($del_id)){
                // 当前栏目信息
                $row = Db::name('arctype')->field('id, parent_id, current_channel, typename')
                    ->where(['id' => $del_id,'is_del' => 1,])
                    ->find();   
                if ($row) {
                    $id_arr = [$row['id']];
                    $list = Db::name('arctype')->field('id,del_method')
                        ->where('id' ,'=', $row['id'])
                        ->whereOr('parent_id','=', $row['id'])
                        ->select()->toArray();
                }else{
                    $result = ['status' => false, 'msg' => '参数错误'];
                    return $result;
                }
                // 需要更新的数据
                $data['is_del']     = 0; // is_del=0为正常数据
                $data['update_time']= getTime(); // 更新修改时间
                $data['del_method'] = 0; // 恢复删除方式为默认
                // 还原数据条件逻辑
                // 栏目逻辑
                $map = 'is_del=1';
                $where  = $map.' and (id='.$del_id.' or parent_id='.$del_id;
                if (0 == intval($row['parent_id'])) {
                    foreach ($list as $value) {
                        if (2 == intval($value['del_method'])) {
                            $where .= ' or parent_id='.$value['id'];
                        }
                    }
                }
                $where .= ')';
                // 文章逻辑
                $where1 = $map.' and typeid in (';
                // 栏目数据更新
                $arctype = Db::name('arctype')->where($where)->select()->toArray();
                foreach ($arctype as $key => $value) {
                    $where = 'is_del=1 and ';
                    if (0 == intval($value['parent_id'])) {
                        $where .= 'id='.$value['id'];
                    }else if(0 < intval($value['parent_id'])){
                        $where .= '(id='.$value['id'].' or id='.$value['parent_id'].')';
                    }
                    if (!in_array($value['id'], $id_arr)) {
                        $where .= ' and del_method=2'; // 不是当前栏目或对应的多语言栏目，则只还原被动删除栏目
                    }
                    Db::name('arctype')->where($where)->update($data);
                    // 还原父级栏目，不还原主动删除的子栏目下的文档
                    if (in_array($value['id'], $id_arr) || 2 == intval($value['del_method'])) {
                        $where1 .= $value['id'].',';
                    }
                }
                $where1 = rtrim($where1,',');
                $where1 .= ') and del_method=2';
                // 还原三级栏目时需要一并还原顶级栏目
                // 多语言处理逻辑
                $parent_id = intval($arctype['0']['parent_id']);
                if (0 < $parent_id) {
                    $where = 'id='.$parent_id;
                    $r1 = Db::name('arctype')->where($where)->find();
                    $parent_id = intval($r1['parent_id']);
                    if (0 < $parent_id) {
                        $where = 'is_del=1 and id='.$parent_id;
                        Db::name('arctype')->where($where)->update($data);
                    }
                }
                // 内容数据更新 -  还原父级栏目，不还原主动删除的子栏目下的文档
                $r = Db::name('archives')->where($where1)->update($data);
                if (false !== $r) {
                    Cache::clear();
                    $result = ['status' => true, 'msg' => '操作成功'];
                    return $result;
                }
            }
            $result = ['status' => false, 'msg' => '操作失败'];
            return $result; 
        }
        $result = ['status' => false, 'msg' => '操作失败'];
        return $result; 
    }

    // 回收站管理 - 栏目删除
    public function arctype_del()
    {
        if (Request::isPost()) {
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $del_id = input('post.del_id/d', 0);
            if(!empty($del_id)){
                // 当前栏目信息
                $row = Db::name('arctype')->field('id, parent_id, current_channel, typename')
                    ->where(['id'=> $del_id, 'is_del'=> 1,])->find();
                if ($row) {
                    $id_arr = $row['id'];
                    $list = Db::name('arctype')->field('id,del_method')
                        ->where('id','=', $id_arr)
                        ->whereOr('parent_id','=', $id_arr)
                        ->select()->toArray();
                }else{
                $result = ['status' => false, 'msg' => '参数错误'];
                return $result;
                }
                // 删除条件逻辑
                // 栏目逻辑
                $map = 'is_del=1';
                $where  = $map.' and (id='.$del_id.' or parent_id='.$del_id;
                if (0 == intval($row['parent_id'])) {
                    foreach ($list as $value) {
                        if (2 == intval($value['del_method'])) {
                            $where .= ' or parent_id='.$value['id'];
                        }
                    }
                }
                $where .= ')';
                // 文章逻辑
                $where1 = $map.' and typeid in (';
                // 查询栏目回收站数据并拼装删除文章逻辑
                $arctype  = Db::name('arctype')->field('id')->where($where)->select()->toArray();
                foreach ($arctype as $key => $value) {
                    $where1 .= $value['id'].',';
                }
                $where1 = rtrim($where1,',');
                $where1 .= ')';
                // 栏目数据删除
                $r = Db::name('arctype')->where($where)->delete();
                // 内容数据删除
                if($r){
                    $r = Db::name('archives')->where($where1)->delete();
                    $msg = '';
                    if (!$r) {$msg = '，文档清空失败！';}
                    $result = ['status' => true, 'msg' => "操作成功".$msg];
                    return $result;
                }
            }
            $result = ['status' => false, 'msg' => "操作失败"];
            return $result;
        }
        $result = ['status' => false, 'msg' => "非法访问"];
        return $result;
    }


    // 回收站管理 - 内容列表
    public function archives_index()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        } 
        if (Request::isAjax()) {
            $post = input('param.');
            if(isset($post['limit'])){
                $limit = $post['limit'];
            }else{
                $limit = 10;
            }
            $condition = [];
            $keywords = isset($post['keywords'])?$post['keywords']:'';
            // 应用搜索条件
            if (!empty($keywords)) {
                $condition[] = ['a.title','=',"{$keywords}"];
            }
            $condition[] = ['a.channel','<>',6]; // 排除单页模型
            $condition[] = ['a.is_del','=',1];
            // 数据查询，搜索出主键ID的值
            $list = DB::name('archives')
                    ->alias('a')
                    ->field("a.aid, a.title, a.typeid, a.update_time, b.typename")
                    ->join('arctype b', 'a.typeid = b.id', 'LEFT')
                    ->where($condition)
                    ->paginate($limit);
            $list1 = $list->items();
            $list1 = array_combine(array_column($list1, 'aid'), $list1);
            foreach ($list1 as $key => $val) {
                $list1[$val['aid']]['update_time'] = pcftime($val['update_time']);
            }
            $result = ['code' => 0, 'data' => $list1,'count'=> $list->total()];
            return $result;
        }
        return $this->fetch();
    }
    
    // 回收站管理 - 内容还原
    public function archives_recovery()
    {
        $id_arr = input('post.del_id/d', 0);
        if(Request::isPost() && !empty($id_arr)){
            if(!$this->popedom["databack"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.databack')];
                    return $result;                    
                }
            }
            $map=[];
            $map[]=['aid','=',$id_arr];
            $map[]=['is_del','=',1];
            // 当前文档信息
            $row = DB::name('archives')->field('aid, title, typeid')->where($map)->select()->toArray();
            if (!empty($row)) {
                $id_arr = get_arr_column($row, 'aid');
                // 关联的栏目ID集合
                $typeids = [];
                $typeidArr = get_arr_column($row, 'typeid');
                $typeidArr = array_unique($typeidArr);
                foreach ($typeidArr as $key => $val) {
                    $pidArr = $this->arctype->getAllPid($val);
                    $typeids = array_merge($typeids, get_arr_column($pidArr, 'id'));
                }
                $typeids = array_unique($typeids);
                if (!empty($typeids)) {
                    // 还原数据
                    $r = Db::name('arctype')->where('id','IN', $typeids)->update(['is_del' => 0,'del_method' => 0,'update_time' => getTime(),]);
                    if ($r) {
                        $r2 = DB::name('archives')->where('aid', 'IN',$id_arr)->update(['is_del' => 0,'del_method' => 0,'update_time' => getTime(),]);
                        if ($r2) {
                            Cache::clear();
                            $result = ['status' => true, 'msg' => '操作成功'];
                            return $result;
                        } else {
                            $result = ['status' => false, 'msg' => '关联栏目还原成功，文档还原失败！'];
                            return $result;
                        }
                    }
                    $result = ['status' => false, 'msg' => '操作失败'];
                    return $result;
                }
            }
            $result = ['status' => false, 'msg' => '参数错误'];
            return $result;
        }
        $result = ['status' => false, 'msg' => '参数错误'];
        return $result;
    }
    // 回收站管理 - 内容删除
    public function archives_del()
    {
        $id_arr = input('post.del_id/d', 0);
        if(Request::isPost() && !empty($id_arr)){
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $map = [];
            $map[] = ['aid','=',$id_arr];
            $map[] = ['is_del','=',1];
            // 当前文档信息
            $row = Db::name('archives')->field('aid, title, channel')->where($map)->select()->toArray();
            if (!empty($row)) {
                $id_arr = get_arr_column($row, 'aid');
                // 内容数据删除
                $r = Db::name('archives')->where('aid','IN', $id_arr)->delete();
                if($r){
                    // 按模型分组，然后进行分组删除
                    $row2Group = group_same_key($row, 'channel');
                    if (!empty($row2Group)) {
                        $channelids = array_keys($row2Group);
                        $channeltypeRow = Db::name('channel_type')->field('id,table')->where('id','IN', $channelids)->column('id,table', 'id');
                        foreach ($row2Group as $key => $val) {
                            $table = $channeltypeRow[$key]['table'];
                            $aidarr_tmp = get_arr_column($val, 'aid');
                            if($channeltypeRow[$key]['id'] == 1){
                                $model = new \app\admin\model\Article();
                                $model->afterDel($id_arr);
                            }else if($channeltypeRow[$key]['id'] == 6){
                                $model = new \app\admin\model\Single();
                                $model->afterDel($id_arr);
                            }else{
                                $model = new \app\admin\model\Custom();
                                $model->afterDel($id_arr,$table);
                            }
                        }
                    }
                    $result = ['status' => true, 'msg' => '操作成功'];
                    return $result;
                }
                $result = ['status' => false, 'msg' => '操作失败'];
                return $result;
            }
        }
        $result = ['status' => false, 'msg' => '参数错误'];
        return $result;
    }

    // 回收站管理 - 自定义变量列表
    public function customvar_index()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            $post = input('param.');
            if(isset($post['limit'])){
                $limit = $post['limit'];
            }else{
                $limit = 10;
            }
            $keywords = isset($post['keywords'])?$post['keywords']:'';
            $condition = [];
            // 应用搜索条件
            if (!empty($keywords)) {
                $condition[] = ['a.attr_name','=',"{$keywords}"];
            }
            $attr_var_names = Db::name('config')->where('is_del' , 1)->column('name', 'name');
            $condition[] = ['a.attr_var_name','IN',array_keys($attr_var_names)];
            $list = Db::name('config_attribute')->alias('a')
            ->field('a.*, b.id')
            ->join('config b', 'b.name = a.attr_var_name', 'LEFT')
            ->where($condition)
            ->order('a.update_time desc')
            ->paginate($limit);
            $list1 = $list->items();
            foreach ($list1 as $key => $value) {
                $list1[$key]['update_time'] = pcftime($value['update_time']);
            }
            $result = ['code' => 0, 'data' => $list1,'count'=> $list->total()];
            return $result;
        }
        return $this->fetch();
    }

    // 回收站管理 - 自定义变量还原
    public function customvar_recovery()
    {
        if (Request::isPost()) {
            if(!$this->popedom["databack"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.databack')];
                    return $result;                    
                }
            } 
            $id_arr = input('del_id/a');
            $id_arr = eyIntval($id_arr);
            if(!empty($id_arr)){
                $map = [];
                $map[] = ['id','IN',$id_arr];
                $map[] = ['is_del','=',1];
                $attr_var_name = Db::name('config')->where($map)->column('name');
                $r = Db::name('config')->where('name', 'IN', $attr_var_name)->update([
                        'is_del'    => 0,
                        'update_time' => getTime(),
                    ]);
                if($r){
                    Cache::clear();
                    $result = ['status' => true, 'msg' => '操作成功'];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => '操作失败'];
                    return $result;
                }
            }
        }
        $result = ['status' => false, 'msg' => '参数错误'];
        return $result;
    }
    
    // 回收站管理 - 自定义变量删除
    public function customvar_del()
    {
        if (Request::isPost()) {
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $id_arr = input('del_id/a');
            $id_arr = eyIntval($id_arr);
            if(!empty($id_arr)){
                $map = [];
                $map[] = ['id','IN',$id_arr];
                $map[] = ['is_del','=',1];
                $attr_var_name = Db::name('config')->where($map)->column('name');
                $r = Db::name('config')->where('name', 'IN', $attr_var_name)->delete();
                if($r){
                    // 同时删除
                    Db::name('config_attribute')->where('attr_var_name', 'IN', $attr_var_name)->delete();
                    $result = ['status' => true, 'msg' => '操作成功'];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => '操作失败'];
                    return $result;
                }
            }
        }
        $result = ['status' => false, 'msg' => '参数错误'];
        return $result;
    }

}